<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>BackBone</title>
        <script type="text/javascript" src="js/main/underscore.js"></script>
        <script type="text/javascript" src="js/main/jquery-1.11.1.min.js"></script>
        <script type="text/javascript" src="js/main/backbone.js"></script>
        <script type="text/javascript">
            window.Hero = Backbone.Model.extend({
                urlRoot: 'database/person.php'
            });
            window.SpriteModel = Backbone.Collection.extend({
                model: Hero
            });
        </script>
        <script type="text/template" id="heroDetail"> 
            <% _.each(heros, function(hero) { %>
            <span class="name"><%=hero.name%></span>
            <span class="hp"><%= hero.hp %></span>
            <ol>
            <% _.each(hero.items, function(item) { %>
            <li><%= item.title %></li>
            <% }); %>
            </ol>
            <% }); %>
        </script>
    </head>
    <body>
        <div id="viewbox"></div>

        <script type="text/javascript">
            window.SpriteView = Backbone.View.extend({
                className: 'view',
                initialize: function() {
                    _.bindAll(this, 'render'); //ทำการผูก object และ function
                    this.model.bind('change', this.render); //ผูกโมเดลกับฟังก์ชั่น    
                    this.template = _.template($('#heroDetail').html()); //แสดงผล ใช้ Template แบบ underscore
                },
                render: function() {
                    var renderedContent = this.template({heros: this.model.toJSON()});
                    $(this.el).html(renderedContent);
                    return this;
                }
            });

            var sniper = new Hero({name: "Sniper", hp: 100, items: [{title: "Rifer"}, {title: "Ring"}]});
            var axe = new Hero({name: "Axe", hp: 150, items: [{title: "Blade"}, {title: "Ring"}]});
            var heros = new SpriteModel([sniper, axe]);
            var heroView = new SpriteView({model: heros});

            sniper.save(undefined, {
                success: function(model, response) {
                    console.log("success");
                },
                error: function() {
                    console.log("error");
                }
            })

            $('#viewbox').append(heroView.render().el);
//            var search_view = new SearchView({el: $("#search_container")});
        </script>
    </body>
</html>